import { deleteChartUsingPOST, listMyChartByPageUsingPOST } from '@/services/bi/chartController';
import { Button, Card, Divider, List, message, Modal, Result } from 'antd';

import { FAILED, RUNNING, SUCCESS, WAIT } from '@/constants';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import Search from 'antd/es/input/Search';
import ReactECharts from 'echarts-for-react';
import moment from 'moment';
import React, { useEffect, useState } from 'react';

/**
 * 我的图表页面
 * @constructor
 */
const MyChartPage: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 4,
    sortField: 'createTime',
    sortOrder: 'desc',
  };
  /**
   * 获取当前用户
   */
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listMyChartByPageUsingPOST(searchParams);
      if (res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
        // 隐藏图表的 title
        if (res.data.records) {
          res.data.records.forEach((data) => {
            if (data.status === SUCCESS) {
              // 图表生成成功才去解析
              const chartOption = JSON.parse(data.genChart ?? '{}');
              chartOption.title = undefined;
              data.genChart = JSON.stringify(chartOption);
            }
          });
        }
      } else {
        message.error('获取图表失败！');
      }
    } catch (e: any) {
      message.error('获取图表失败！', e.message);
    }
    setLoading(false);
  };

  const doDelete = async (chartId: any) => {
    // 删除数据
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这个图表吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await deleteChartUsingPOST({ id: chartId });
          if (res.code === 0) {
            message.success('删除成功');
            // 删除成功后重新加载图表数据
            loadData();
          } else {
            message.error('删除失败，' + res.message);
          }
        } catch (e: any) {
          message.error('删除失败，' + e.message);
        }
      },
    });
  };

  /**
   * 俗称 钩子
   * 首次 渲染页面 以及 deps中的数组 变化时会执行
   */
  useEffect(() => {
    loadData();
  }, [searchParams]);

  return (
    <div className="my-chart-page">
      <Search
        placeholder="请输入图表名称"
        enterButton="搜索"
        size="large"
        loading={loading}
        onSearch={(values) => {
          setSearchParams({
            // 设置搜索条件
            ...initSearchParams,
            name: values,
          });
        }}
      />
      <Divider />
      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        itemLayout="vertical"
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize,
            });
          },
          defaultCurrent: searchParams.current,
          defaultPageSize: searchParams.pageSize,
          total: total,
        }}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card style={{ width: '100%' }}>
              <List.Item.Meta
                // avatar={<Avatar src={currentUser?.userAvatar} />}
                title={item.name}
                description={item.chartType ? '图表类型：' + item.chartType : undefined}
              />
              <>
                {item.status === SUCCESS && (
                  <>
                    {'分析目标：' + item.goal}
                    <div style={{ marginBottom: 16 }} />
                    <ReactECharts option={JSON.parse(item.genChart ?? '{}')} />
                    {'分析结果：' + item.genResult}
                    <div style={{ marginBottom: 16 }} />
                    {'生成时间：' + moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')}
                  </>
                )}
                {item.status === WAIT && (
                  <>
                    <Result
                      status="warning"
                      title="待生成~"
                      subTitle={item.execMessage ?? '系统繁忙，请耐心等候~'}
                    />
                  </>
                )}
                {item.status === RUNNING && (
                  <>
                    <Result status="info" title="图表生成中~" subTitle={item.execMessage} />
                  </>
                )}
                {item.status === FAILED && (
                  <>
                    <Result status="error" title="图表生成失败~" subTitle={item.execMessage} />
                  </>
                )}
                <Button
                  type="primary"
                  danger
                  onClick={() => doDelete(item.id)}
                  style={{ marginLeft: 350 }}
                >
                  删除
                </Button>
              </>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};
export default MyChartPage;
